<template>
  <div class="app-wrapper">
    <div class="banner">
      <div class="banner-file" v-if="filename">
        <i
          class="el-icon-folder-opened"
          style="font-size: 25px; margin-right: 5px; color: #e6a23c"
        ></i>
        {{ filename }}
      </div>
      <a href="/" class="banner-title">文档展示器</a>
      <i
        class="el-icon-full-screen screenfull-style"
        @click.stop="toFullScreen"
      ></i>
      <div class="banner-right">
        <el-button type="primary" round size="small" @click="handleUpload">
          上传预览
        </el-button>
        <el-button type="primary" round size="small" @click="downloadFile"
          >下载</el-button
        >
        <input
          v-show="false"
          type="file"
          ref="fileButton"
          @change="handleChange"
        />
      </div>
    </div>
    <div class="container">
      <div
        v-if="!filename"
        class="content"
        ref="screenFullContent"
        v-loading="loading"
        element-loading-text="正在加载中，请耐心等待..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-empty style="margin-top: 100px">
          <el-button type="primary" round @click="handleUpload">
            上传预览
          </el-button>
        </el-empty>
      </div>
      <div v-else class="output" ref="output">
        <Pdf :pdf="curFile.src" v-if="curFile.extend == 'pdf'"></Pdf>
        <Excel
          style="height: calc(100vh - 90px)"
          :excel="curFile.src"
          v-if="curFile.extend == 'xls' || curFile.extend == 'xlsx'"
        ></Excel>
        <Word
          :docx="curFile.src"
          v-if="curFile.extend == 'doc' || curFile.extend == 'docx'"
        ></Word>
        <pptx
          :file="curFile.file"
          v-if="curFile.extend == 'ppt' || curFile.extend == 'pptx'"
          :key="refreshPptKey"
        ></pptx>
        <MyVideo
          style="width: 900px; height: 600px; margin: 100px auto"
          :video="curFile.video"
          v-if="curFile.extend == 'video'"
        ></MyVideo>
        <Music
          :musicList="curFile.musicList"
          v-if="curFile.extend == 'music'"
        ></Music>
        <MyImage :src="curFile.src" v-if="curFile.extend == 'image'"></MyImage>
        <Codemirror
          v-if="curFile.extend == 'text'"
          style="top: 130px"
          :initCodeValue="curFile.codeValue"
          :initEditorMode="curFile.cmMode"
          :key="refreshCodemirrorKey"
        ></Codemirror>
        <div v-if="curFile.extend == undefined" class="desc">
          <p>
            不支持{{ extend }}格式的在线预览，请下载后预览或转换为支持的格式
          </p>
          <p>
            支持docx, xlsx, pptx, pdf,
            以及纯文本/代码格式和各种图片、视频格式的在线预览
          </p>
        </div>
      </div>
      <div class="link-style"><a href="http://qkongtao.cn/">Nickの博客</a></div>
    </div>
  </div>
</template>

<script>
import Codemirror from "../components/codemirror/index.vue";
import Excel from "../components/excel/Excel.vue";
import MyVideo from "../components/mp4/Xgplayer.vue";
import Music from "../components/music/Music.vue";
import Pdf from "../components/pdf/Pdf.vue";
import pptx from "../components/pptx/pptx.vue";
import Word from "../components/word/Word.vue";
import MyImage from "../components/image/Image.vue";
import download from "../utils/download";
import screenfull from "../utils/screenfull";

export default {
  components: {
    Codemirror,
    Excel,
    Music,
    MyVideo,
    Pdf,
    pptx,
    Word,
    MyImage,
  },
  data() {
    return {
      // 加载状态跟踪
      loading: false,
      // 文件拓展名
      extend: "",
      curFile: {},
      refreshCodemirrorKey: 0,
      refreshPptKey: 0,
      file: null,
      filename: "",
    };
  },
  methods: {
    async handleChange(e) {
      this.loading = true;
      try {
        // 取得上传文件
        const [file] = e.target.files;
        this.file = file;
        // 取得文件名
        const { name } = file;
        this.filename = name;
        // 取得扩展名
        this.extend = this.getExtend(name);
        // 对文件类型进行操作
        this.switchFileType(this.extend, file);

        this.loading = false;
      } catch (e) {
        console.error(e);
      } finally {
        this.loading = false;
      }
    },

    // 对文件类型进行操作
    switchFileType(extend, file) {
      // console.log("extend :>> ", extend);
      // console.log("file :>> ", file);
      // console.log("URL.createObjectURL(file), :>> ", URL.createObjectURL(file));
      var fileTypes = [
        {
          // 文档类型
          accepts: ["docx", "doc", "xls", "xlsx", "pdf", "ppt", "pptx"],
          data: {
            extend: extend,
            src: URL.createObjectURL(file),
            file: file,
          },
        },
        {
          // 图片类型
          accepts: ["gif", "jpg", "jpeg", "bmp", "tiff", "tif", "png", "svg"],
          data: {
            extend: "image",
            src: URL.createObjectURL(file),
          },
        },
        {
          // 视频类型
          accepts: [
            "avi",
            "mpg",
            "mpe",
            "mpeg",
            "asf",
            "wmv",
            "mov",
            "qt",
            "rm",
            "mp4",
            "flv",
            "m4v",
            "webm",
            "ogv",
            "ogg",
          ],
          data: {
            extend: "video",
            video: {
              src: URL.createObjectURL(file),
            },
          },
        },
        {
          // 音频类型
          accepts: [
            "mp3",
            "wav",
            "wma",
            "mpa",
            "ram",
            "ra",
            "aac",
            "aif",
            "m4a",
          ],
          data: {
            extend: "music",
            musicList: [
              {
                name: file.name,
                artist: "未知歌手",
                cover:
                  "https://upyun.qkongtao.cn/chevereto/2022/09/29/logo.th.png",
                url: URL.createObjectURL(file),
              },
            ],
          },
        },
        {
          // 文本类型

          accepts: [
            "txt",
            "json",
            "java",
            "sql",
            "js",
            "css",
            "xml",
            "html",
            "yaml",
            "md",
            "py",
          ],
          data: { extend: "text", cmMode: extend, codeValue: "" },
        },
      ];

      // 遍历返回
      var _this = this;
      var flag = 0;
      fileTypes.forEach(async (element) => {
        if (element.accepts.indexOf(extend) > -1) {
          if (element.data.extend == "text") {
            // 同步获取到数据
            const data = await this.readFileAsync(file);
            element.data.codeValue = data;
            _this.refreshCodemirrorKey++;
          } else if (
            element.data.extend == "ppt" ||
            element.data.extend == "pptx"
          ) {
            _this.refreshPptKey++;
          }
          _this.curFile = element.data;
          flag = 1;
        }
      });
      if (flag == 0) {
        this.curFile = {};
      }
    },
    // 点击上传
    handleUpload() {
      this.$refs.fileButton?.click?.();
    },
    //下载附件
    downloadFile() {
      var fileName = this.filename;
      var file = this.file;
      if (file == undefined) {
        alert("文件不存在！");
        return;
      }
      download({
        fileName: fileName,
        file: file,
      }).then((res) => {
        console.log(res);
      });
    },

    // 点击全屏
    toFullScreen() {
      var ref = this.$refs.screenFullContent;
      if (ref) {
        screenfull.toggle(ref);
      } else {
        screenfull.toggle();
      }
    },

    // 获取文件后缀名
    getExtend(name) {
      const dot = name.lastIndexOf(".");
      return name.substr(dot + 1);
    },
    // 读取文本文件内容
    readFileAsync(file) {
      return new Promise((resolve, reject) => {
        // 读取文件里面的内容返回
        var reader = new FileReader();
        // 以文本格式读取文件
        reader.readAsText(file, "UTF-8");
        reader.onload = function (event) {
          resolve(event.target.result);
        };
        reader.onerror = function (event) {
          reject(event.target);
        };
      });
    },
  },
};
</script>

<style scoped>
.app-wrapper {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}
.banner {
  height: 60px;
  width: 100%;
  /* padding: 0 30px; */
  background-color: #323639;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #f2ffff;
  position: relative;

  /* box-shadow: 0 6px 8px 4px #76767614; */
  /* background: white;
  background: linear-gradient(
    to right bottom,
    rgba(255, 255, 255, 0.7),
    rgba(255, 255, 255, 0.3)
  );
  z-index: 2;
  backdrop-filter: blur($blur); */
}
.banner-file {
  padding-left: 10px;
  position: absolute;
  left: 15px;
  top: 15px;
}
.banner-title {
  text-decoration: none;
  color: #ededed;
  font-size: 20px;
  font-weight: bold;
  letter-spacing: 2px;

  font-family: "Lucida Sans", "Lucida Sans Regular", "Lucida Grande",
    "Lucida Sans Unicode", Geneva, Verdana, sans-serif;
}
.banner-right {
  /* padding-left: 20px; */
  position: absolute;
  right: 15px;
  top: 15px;
}
.output {
}
.content {
  height: calc(100vh - 90px);
  width: 100%;
  overflow-y: auto;
  background-color: #525659;
  color: #f2ffff;
}
.link-style {
  position: fixed;
  width: 100%;
  height: 30px;
  line-height: 30px;
  left: 50%;
  text-align: center;
  bottom: 0px;
  transform: translate(-50%);
  z-index: 99999;
  background-color: #525659;
}
.link-style a {
  text-decoration: none;
  color: #f2ffff;
}
.screenfull-style {
  margin-left: 10px;
  font-size: 25px;
}

.desc {
  width: 600px;
  margin: 200px auto;
  text-align: center;
  font-size: 18px;
  /* color: #f2ffff; */
}
</style>
